package com.lx.es.test;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lx.es.entity.User;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

/**
 * @author wcy
 */
public class ESTest_Doc_Insert {

    public static void main(String[] args) throws IOException {

        //创建ES客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("114.116.253.253",9200,"http")));

        IndexRequest request = new IndexRequest();

        request.index("user").id("1004");

        User user = new User();
        user.setName("wangwu4");
        user.setAge(60);
        user.setSex("男");

        ObjectMapper objectMapper = new ObjectMapper();

        String userJson = objectMapper.writeValueAsString(user);

        request.source(userJson, XContentType.JSON);

        IndexResponse response = esClient.index(request, RequestOptions.DEFAULT);

        System.out.println("_index:" + response.getIndex());
        System.out.println("_id:" + response.getId());
        System.out.println("_result:" + response.getResult());

        //关闭客户端
        esClient.close();

    }
}
